package com.wuxin.ssm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
 * @program: untitled
 * @ClassName ImageController
 * @description: 验证码的生成
 * @author: 李尧坤
 * @create: 2024−12-10 18:53
 * @Version 1.0
 **/
@Controller
public class ImageController {
    /**
     * 三原色 0-225 RGB
     */
    /**
     * 得到颜色
     * @param min
     * @param max
     * @return
     */
    public static Color getRandomColor(int min, int max){
        Random random = new Random();
        if(min>255){
            min=255;
        }
        if(max>255){
            max=255;
        }
        //   max =200  min =168
        int red = random.nextInt(max-min)+min;
        int green = random.nextInt(max-min)+min;
        int blue = random.nextInt(max-min)+min;
        //得到一个颜色值
        return  new Color(red,green,blue);
    }


    @RequestMapping("/yzmcontroller.action")
    @ResponseBody
    public void yzm(HttpSession session, HttpServletResponse response){
        //规定画图的地方
        int width=60,height=20;

        //的 BufferedImage类描述了一个 Image与访问图像数据缓冲区。
        BufferedImage pic=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //得到画布
        Graphics gc = pic.getGraphics();
        //给画布设置颜色
        gc.setColor(getRandomColor(200,253));
        //画一个矩形
        gc.fillRect(0,0,width,height);
        //设置字体
        gc.setFont(new Font("宋体",Font.PLAIN,20));

        Random r = new Random();
        //画干扰线
        for (int i = 0; i < 100; i++) {
            int x1=r.nextInt(width);
            int y1=r.nextInt(height);

            int x2=r.nextInt(15);
            int y2=r.nextInt(15);
            //设置干扰线颜色
            gc.setColor(getRandomColor(160,199));
            gc.drawLine(x1,y1,x2,y2);
        }

        //画干扰点
        for (int i = 0; i < 100; i++) {
            int x1=r.nextInt(width);
            int y1=r.nextInt(height);


            //设置干扰线颜色
            gc.setColor(getRandomColor(130,159));
            gc.drawOval(x1,y1,0,0);
        }

        //生成数字
        String RS =r.nextInt(9000)+1000+"";
        gc.setColor(getRandomColor(80,129));
        //画验证码
        gc.drawString(RS,10,16);
        //销毁画布
        gc.dispose();
        //存验证码
        session.setAttribute("random",RS);

        try {
            //将图片写到页面上
            ImageIO.write(pic,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


}
